<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue';
import type { Component } from 'vue';
import { getColorPalette, mixColor } from '@sa/utils';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import { useThemeStore } from '@/store/modules/theme';
import { loginModuleRecord } from '@/constants/app';
// import bgImage from '@/assets/imgs/log_bj7.png';
import bgImage from '@/assets/imgs/lg_bj17.jpg';

// import wBgImage from '@/assets/imgs/pic.png';
import wBgImage from '@/assets/imgs/pic5.jpg';

import logoImage from '@/assets/imgs/cdl_logo.png';
import PwdLogin from './modules/pwd-login.vue';
import CodeLogin from './modules/code-login.vue';
import Register from './modules/register.vue';
import ResetPwd from './modules/reset-pwd.vue';
import BindWechat from './modules/bind-wechat.vue';

interface Props {
  /** The login module */
  module?: UnionKey.LoginModule;
}

const props = defineProps<Props>();

const appStore = useAppStore();
const themeStore = useThemeStore();

interface LoginModule {
  label: string;
  component: Component;
}

const moduleMap: Record<UnionKey.LoginModule, LoginModule> = {
  'pwd-login': { label: loginModuleRecord['pwd-login'], component: PwdLogin },
  'code-login': { label: loginModuleRecord['code-login'], component: CodeLogin },
  register: { label: loginModuleRecord.register, component: Register },
  'reset-pwd': { label: loginModuleRecord['reset-pwd'], component: ResetPwd },
  'bind-wechat': { label: loginModuleRecord['bind-wechat'], component: BindWechat }
};

const activeModule = computed(() => moduleMap[props.module || 'pwd-login']);

const bgThemeColor = computed(() =>
  themeStore.darkMode ? getColorPalette(themeStore.themeColor, 7) : themeStore.themeColor
);

const bgColor = computed(() => {
  const COLOR_WHITE = '#ffffff';

  const ratio = themeStore.darkMode ? 0.5 : 0.2;

  return mixColor(COLOR_WHITE, themeStore.themeColor, ratio);
});

// 背景图片地址
const bgImageUrl = computed(() => `url(${bgImage})`);
const logoImageUrl = computed(() => logoImage);

// 星空动画相关
const canvasRef = ref<HTMLCanvasElement | null>(null);
const outerCanvasRef = ref<HTMLCanvasElement | null>(null);
let animationFrameId: number;
let outerAnimationFrameId: number;
let stars: { x: number; y: number; size: number; speedX: number; speedY: number; opacity: number; blinkSpeed: number }[] = [];
let outerStars: { x: number; y: number; size: number; speedX: number; speedY: number; opacity: number; blinkSpeed: number }[] = [];

// 初始化星星
const initStars = (canvas: HTMLCanvasElement) => {
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 创建星星数组
  stars = [];
  const starCount = Math.floor((canvas.width * canvas.height) / 3000); // 根据屏幕密度确定星星数量

  for (let i = 0; i < starCount; i++) {
    stars.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      size: Math.random() * 2 + 1,
      speedX: (Math.random() - 0.5) * 0.5,
      speedY: (Math.random() - 0.5) * 0.5,
      opacity: Math.random(),
      blinkSpeed: Math.random() * 0.02 + 0.005
    });
  }
};

// 初始化外部星星
const initOuterStars = (canvas: HTMLCanvasElement) => {
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 创建星星数组
  outerStars = [];
  const starCount = Math.floor((canvas.width * canvas.height) / 3000); // 根据屏幕密度确定星星数量

  for (let i = 0; i < starCount; i++) {
    outerStars.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      size: Math.random() * 2 + 1,
      speedX: (Math.random() - 0.5) * 0.5,
      speedY: (Math.random() - 0.5) * 0.5,
      opacity: Math.random(),
      blinkSpeed: Math.random() * 0.02 + 0.005
    });
  }
};

// 绘制星空动画
const drawStars = () => {
  if (!canvasRef.value) return;

  const canvas = canvasRef.value;
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制并更新星星
  stars.forEach(star => {
    // 更新星星位置
    star.x += star.speedX;
    star.y += star.speedY;

    // 边界检查，让星星从另一边出现
    if (star.x > canvas.width) star.x = 0;
    if (star.x < 0) star.x = canvas.width;
    if (star.y > canvas.height) star.y = 0;
    if (star.y < 0) star.y = canvas.height;

    // 更新星星透明度（闪烁效果）
    star.opacity += star.blinkSpeed;
    if (star.opacity > 1 || star.opacity < 0.2) {
      star.blinkSpeed = -star.blinkSpeed;
    }

    // 绘制星星
    ctx.beginPath();
    ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
    ctx.fillStyle = `rgba(255, 255, 255, ${star.opacity})`;
    ctx.fill();
  });

  animationFrameId = requestAnimationFrame(drawStars);
};

// 绘制外部星空动画
const drawOuterStars = () => {
  if (!outerCanvasRef.value) return;

  const canvas = outerCanvasRef.value;
  const ctx = canvas.getContext('2d');
  if (!ctx) return;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 绘制并更新星星
  outerStars.forEach(star => {
    // 更新星星位置
    star.x += star.speedX;
    star.y += star.speedY;

    // 边界检查，让星星从另一边出现
    if (star.x > canvas.width) star.x = 0;
    if (star.x < 0) star.x = canvas.width;
    if (star.y > canvas.height) star.y = 0;
    if (star.y < 0) star.y = canvas.height;

    // 更新星星透明度（闪烁效果）
    star.opacity += star.blinkSpeed;
    if (star.opacity > 1 || star.opacity < 0.2) {
      star.blinkSpeed = -star.blinkSpeed;
    }

    // 绘制星星
    ctx.beginPath();
    ctx.arc(star.x, star.y, star.size, 0, Math.PI * 2);
    // ctx.fillStyle = `rgba(85, 212, 218, ${star.opacity})`; // #55D4DA 的 RGB 值是 (85, 212, 218)
    ctx.fillStyle = `rgba(95, 158, 160, ${star.opacity})`;
    // ctx.fillStyle = `rgba(255, 255, 255, ${star.opacity})`;
    ctx.fill();
  });

  outerAnimationFrameId = requestAnimationFrame(drawOuterStars);
};

// 调整画布大小
const resizeCanvas = () => {
  if (!canvasRef.value) return;

  const canvas = canvasRef.value;
  const parent = canvas.parentElement;
  if (parent) {
    canvas.width = parent.clientWidth;
    canvas.height = parent.clientHeight;
    initStars(canvas);
  }
};

// 调整外部画布大小
const resizeOuterCanvas = () => {
  if (!outerCanvasRef.value) return;

  const canvas = outerCanvasRef.value;
  const parent = canvas.parentElement;
  if (parent) {
    canvas.width = parent.clientWidth;
    canvas.height = parent.clientHeight;
    initOuterStars(canvas);
  }
};

// 窗口大小变化处理
const handleResize = () => {
  resizeCanvas();
  resizeOuterCanvas();
};

onMounted(() => {
  resizeCanvas();
  resizeOuterCanvas();
  drawStars();
  drawOuterStars();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  cancelAnimationFrame(animationFrameId);
  cancelAnimationFrame(outerAnimationFrameId);
  window.removeEventListener('resize', handleResize);
});
</script>

<template>
  <!-- background-color: #5F9EA0; -->
   <!-- background: black; -->
      <!-- teal -->
       <!-- F7FAFC -->
  <!-- <div class="fixed inset-0 -z-1 bg-cover bg-center bg-attachment-fixed" style="background: #F5F7FB;"></div> -->
  <div class="fixed inset-0 -z-1 bg-cover bg-center bg-attachment-fixed"  :style="{ backgroundImage: `url(${wBgImage})` }">
    <div class="absolute inset-0 bg-black bg-opacity-2"></div>
  </div>
  <!-- <canvas ref="outerCanvasRef" class="fixed inset-0 -z-1"></canvas> -->
  <div class="relative size-full flex">
    <div class="absolute inset-0 flex items-center justify-center">
      <div class="w-900px h-500px flex rounded-2xl overflow-hidden shadow-xl">
        <!-- 左侧背景图区域 -->
        <div class="w-60% h-full relative">
          <div class="absolute inset-0 bg-cover bg-center" :style="{ backgroundImage: `url(${bgImage})` }"></div>
          <!-- 添加蒙层 -->
          <div class="absolute inset-0 bg-black bg-opacity-2"></div>
          <!-- <canvas ref="canvasRef" class="absolute inset-0"></canvas> -->
          <!-- <div class="absolute inset-0 bg-black bg-opacity-40"></div> -->
          <div class="absolute inset-0 flex flex-col items-center justify-center text-white p-20px">
            <div class="text-38px font-bold mb-20px" style="color: #4B4B4B;"><span style="color: #175D8E;">智动力</span> 智能报价系统</div>
          </div>
        </div>

        <!-- 右侧登录表单区域 -->
        <div class="w-40% h-full bg-white flex flex-col">
          <div class="absolute inset-0 bg-black bg-opacity-0.6"></div>

          <div class="flex flex-col justify-start p-30px">
            <div class="mb-30px" style="display: flex; align-items: center;">
              <img :src="logoImageUrl" alt="logo" class="w-140px h-30px" />
              <h3 class="text-24px text-gray-800 font-bold" style="margin-left: 20px; letter-spacing: 2px;">欢迎登录</h3>
            </div>

            <main>
              <div class="pt-10px">
                <Transition :name="themeStore.page.animateMode" mode="out-in" appear>
                  <component :is="activeModule.component" />
                </Transition>
              </div>
            </main>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.bg {
  // background: url(/src/assets/imgs/log-b2.jpg) no-repeat left center;
  background-size: cover;
}

.tech-bg-animation {
  position: fixed;
  inset: 0;
  overflow: hidden;
  z-index: -1;
  pointer-events: none;
}

/* 科技感网格背景 */
.tech-grid {
  position: absolute;
  inset: 0;
  background-image:
    linear-gradient(rgba(23, 93, 142, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(23, 93, 142, 0.1) 1px, transparent 1px);
  background-size: 30px 30px;
  animation: gridMove 10s linear infinite;
}

@keyframes gridMove {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(30px, 30px);
  }
}

/* 扫描线效果 */
.scanner-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, rgba(0, 255, 128, 0.6), transparent);
  box-shadow: 0 0 10px rgba(0, 255, 128, 0.8);
  animation: scan 4s linear infinite;
}

@keyframes scan {
  0% {
    top: 0%;
  }
  100% {
    top: 100%;
  }
}

/* 浮动粒子 */
.floating-particles {
  position: absolute;
  inset: 0;
  z-index: 2;
}

.particle {
  position: absolute;
  background: rgba(0, 255, 128, 0.8);
  border-radius: 50%;
  box-shadow: 0 0 10px rgba(0, 255, 128, 1);
  animation: float 5s infinite linear;
}

@keyframes float {
  0% {
    transform: translateY(0) translateX(0);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    transform: translateY(-100px) translateX(20px);
    opacity: 0;
  }
}
</style>
